package com.onetech.adrewards.free.dialogs;

import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.opengl.Visibility;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.NewPermissionsRequest;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.ProfilePictureView;
import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
public class ShareFacebookDialog extends Activity implements OnClickListener {
	private static final List<String> PERMISSIONS = Arrays
			.asList("publish_actions");
	private final String PENDING_ACTION_BUNDLE_KEY = "com.onetech.adrewards.free:PendingAction";
	private LoginButton loginButton;

	private PendingAction pendingAction = PendingAction.NONE;
	private GraphUser user;
	private Button mBtnShare;
	
	private ImageView mExitBtn;
	
	private TextView mLoginText;
	private TextView mShareText;
	private ProgressDialog mPrDialog = null;
	private String shareText = "";

	private enum PendingAction {
		NONE, POST_PHOTO, POST_STATUS_UPDATE
	}

	private UiLifecycleHelper uiHelper;

	
	private Session.StatusCallback statusCallback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
				
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		uiHelper = new UiLifecycleHelper(this, statusCallback);
		uiHelper.onCreate(savedInstanceState);

		if (savedInstanceState != null) {
			String name = savedInstanceState
					.getString(PENDING_ACTION_BUNDLE_KEY);
			pendingAction = PendingAction.valueOf(name);
		}

		setContentView(R.layout.dialog_facebook_share_layout);

		loginButton = (LoginButton) findViewById(R.id.fb_btnLogin);
		loginButton
				.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
					@Override
					public void onUserInfoFetched(GraphUser user) {
						ShareFacebookDialog.this.user = user;
						updateUI();
						// It's possible that we were waiting for this.user to
						// be
						// populated in order to post a
						// status update.
						handlePendingAction("");
					}
				});

		Bundle bundle = getIntent().getExtras();
		 
		 if(bundle != null)
		 {
			 shareText = bundle.getString(Intent.EXTRA_TEXT);
			 
		 }
		

		mBtnShare = (Button) findViewById(R.id.fb_btnShare);
	
		mExitBtn=(ImageView)findViewById(R.id.exitDialogBtn);
		mExitBtn.setOnClickListener(this);
		mBtnShare.setOnClickListener(this);		
		
		mShareText = (EditText) findViewById(R.id.fbShareText);
		mShareText.setText(shareText);
		mLoginText = (TextView) findViewById(R.id.fbLoginText);
		
		

		
		mPrDialog = new ProgressDialog(ShareFacebookDialog.this);
		mPrDialog.setCancelable(false);
		mPrDialog.setMessage(getString(R.string.socail_sharing_message));
		
		
		
		
	}
	private void shareFacebook() {
		Session session = Session.getActiveSession();
		if (session != null && session.isOpened()) {
			if (mPrDialog == null) {
				mPrDialog = new ProgressDialog(ShareFacebookDialog.this);
				mPrDialog.setCancelable(false);
				mPrDialog.setMessage(getString(R.string.socail_sharing_message));
			}
			String comment = shareText;
//			try {
//				comment = mEdtComment.getText().toString();
//			} catch (Exception e) {
//				comment = "";
//			}
			if(comment.trim().length()<1){
				Toast.makeText(getApplicationContext(), getString(R.string.social_empty_message), Toast.LENGTH_LONG).show();
				return;
			}
			mPrDialog.show();
			onClickPostPhoto(comment);
			CommonModel.getInstance().doSocialCoin("7");
			
			// ShareOnFacebookActivity.this.finish();
		} else {
			AdrewadsUtils.showMessage(ShareFacebookDialog.this,
					getString(R.string.please_login_to_share_on_facebook));
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
		uiHelper.onResume();

		updateUI();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);

		outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (pendingAction != PendingAction.NONE
				&& (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
			pendingAction = PendingAction.NONE;
		} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
			handlePendingAction("");
		}
		updateUI();
	}

	private void updateUI() {
		Session session = Session.getActiveSession();
		boolean enableButtons = (session != null && session.isOpened());

		if (enableButtons) {
			
			mLoginText.setVisibility(View.GONE);
			//mShareText.setVisibility(View.VISIBLE);
			//mBtnShare.setVisibility(View.VISIBLE);
			
		} else {
			mLoginText.setVisibility(View.VISIBLE);
			//mShareText.setVisibility(View.GONE);
			//mBtnShare.setVisibility(View.GONE);
		}
	}

	@SuppressWarnings("incomplete-switch")
	private void handlePendingAction(String comment) {
		PendingAction previouslyPendingAction = pendingAction;
		// These actions may re-set pendingAction if they are still pending, but
		// we assume they
		// will succeed.
		pendingAction = PendingAction.NONE;

		switch (previouslyPendingAction) {
		case POST_PHOTO:
			// postPhoto();
			postToFacebook(comment);
			break;
		case POST_STATUS_UPDATE:
			postStatusUpdate();
			break;
		}
	}
	
	private void postStatusUpdate() {
		if (user != null && hasPublishPermission()) {
			final String message = "";
			Request request = Request.newStatusUpdateRequest(
					Session.getActiveSession(), message,
					new Request.Callback() {
						@Override
						public void onCompleted(Response response) {
							// showPublishResult(message,
							// response.getGraphObject(),
							// response.getError());
							Log.d("TEST",
									"response.getError()="
											+ response.getError());
						}
					});
			request.executeAsync();
		} else {
			pendingAction = PendingAction.POST_STATUS_UPDATE;
		}
	}

	private void postToFacebook(String review) {
		do {
			

			try {
				String link = getString(R.string.share_link);

				Bundle postParams = new Bundle();
				postParams.putString("message", review);
				postParams.putString("name", getString(R.string.share_name));
				postParams.putString("caption", getString(R.string.share_caption));
				postParams.putString("link", link);
				postParams.putString("description", getString(R.string.share_description));
				postParams.putString("picture", getString(R.string.share_image_cover));
				
//				postParams.putString("message", "message");
//				postParams.putString("name", "name");
//				postParams.putString("caption", "caption");
//				postParams.putString("link", "http://test.adreward.onetechonline.com");
//				postParams.putString("description", "description");
//				postParams.putString("picture", "http://test.adreward.onetechonline.com/images/ban_invitefriend.jpg");
				

				
				Request request;

				request = new Request(Session.getActiveSession(), "me/feed",
						postParams, HttpMethod.POST, new Request.Callback() {

							@Override
							public void onCompleted(Response response) {
								if (response != null
										&& response.getError() == null) {
									ShareFacebookDialog.this
											.runOnUiThread(new Runnable() {

												@Override
												public void run() {
													AdrewadsUtils.showMessage(ShareFacebookDialog.this,
																	getString(R.string.share_successful));
												}
											});
								} else {
									ShareFacebookDialog.this
											.runOnUiThread(new Runnable() {

												@Override
												public void run() {
													AdrewadsUtils.showMessage(ShareFacebookDialog.this,
															getString(R.string.share_error));
												}
											});
								}
								if (mPrDialog != null && mPrDialog.isShowing())
									mPrDialog.dismiss();
								ShareFacebookDialog.this.finish();
							}
							
						});

				request.executeAsync();
			} catch (Exception e) {
				
			}
		} while (false);
	}

	private void onClickPostPhoto(String comment) {
		performPublish(PendingAction.POST_PHOTO, comment);
	}

	private boolean hasPublishPermission() {
		Session session = Session.getActiveSession();
		return session != null
				&& session.getPermissions().contains("publish_actions");
	}

	private void performPublish(final PendingAction action, String comment) {
		Session session = Session.getActiveSession();
		if (session != null) {
			pendingAction = action;
			if (hasPublishPermission()) {
				// We can do the action right away.
				handlePendingAction(comment);
			} else {
				// We need to get new permissions, then complete the action
				// when we get called back.
				NewPermissionsRequest newPP = new NewPermissionsRequest(
						ShareFacebookDialog.this, PERMISSIONS);
				newPP.setDefaultAudience(SessionDefaultAudience.EVERYONE);
				session.requestNewPublishPermissions(newPP);
			}
		}

	}
	@Override
	public void onClick(View v) {
		int id=v.getId();
		switch (id) {
		case R.id.fb_btnShare:
			shareFacebook();
			break;
		case R.id.exitDialogBtn:
			finish();
			break;
		default:
			break;
		}
	}
}
